import { USER_LOGIN, USER_LOGOUT } from "../actions/action-types"

const username = localStorage.getItem('username') || sessionStorage.getItem('username') || ''
const token = localStorage.getItem('token') || sessionStorage.getItem('token') || ''
const isLogin = !!username && !!token

const initialState = {
  username,
  token,
  isLogin // 标记用户是否登录
}

// reducer 纯函数，根据动作类型判断如何更新状态，会返回更新后的新状态值
export default (state = initialState, { type, payload }) => {
  switch (type) {
    case USER_LOGIN: // 登录
      return payload
    case USER_LOGOUT: // 退出
      return {
        username: '',
        token: '',
        isLogin: false
      }
    default:
      return state
  }
}
